package com.example.pro1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.example.json.Contacts;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
	private Button bt_rawData,bt_analysis;
	private TextView tv_json;
	private Handler handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what){
				case 1:
					String text=(String) msg.obj;
					tv_json.setText(text);
					break;
				case 2:
					break;
				}
			}
		};
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initLayout();
        bt_rawData.setOnClickListener(this);
        bt_analysis.setOnClickListener(this);
    }

	private void initLayout() {
		bt_rawData=(Button) findViewById(R.id.bt_rawData);
		bt_analysis=(Button) findViewById(R.id.bt_analysis);
		tv_json=(TextView) findViewById(R.id.tv_json);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.bt_rawData:
			getJsonData();
			break;
		case R.id.bt_analysis:
			setListView();
			break;
		default:
			break;
		}
	}

	private void setListView() {
		Intent intent=new Intent(MainActivity.this,ListViewActivity.class);
		startActivity(intent);
	}

	private void getJsonData() {
		OkHttpClient client=new OkHttpClient();
		Request request=new Request.Builder()
									.url("http://176.122.140.84/contact.json")
									.build();
		client.newCall(request).enqueue(new Callback() {
			
			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				List<Contacts> list=new ArrayList<Contacts>();
				String json=arg1.body().string();
				Gson gson=new Gson();
				list= gson.fromJson(json,new TypeToken<List<Contacts>>(){}.getType());
				Message message=new Message();
				message.obj=json;
				message.what=1;
				handler.sendMessage(message);
			}
			
			@Override
			public void onFailure(Call arg0, IOException arg1) {
				
			}
		});
	}
}
